package com.zFace.多线程轮流打印;

import java.util.concurrent.Semaphore;

/**
 * 用 Semaphore 实现 三个线程轮流打印十次
 */
public class Demo5 {

	private static int index = 1;

	public static void main(String[] args) throws InterruptedException {
		Semaphore semaphore1 = new Semaphore(1);
		Semaphore semaphore2 = new Semaphore(0);
		Semaphore semaphore3 = new Semaphore(0);

		Thread t1 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						semaphore1.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("a");
					semaphore2.release();
				}
			}
		});
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						semaphore2.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("b");
					semaphore3.release();
				}
			}
		});
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						semaphore3.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("c");
					semaphore1.release();
				}
			}
		});
		t1.start();
		t2.start();
		t3.start();
	}
}
